package com.su.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取文件下载路径
        String realPath = this.getServletContext().getRealPath("F:\\Junior_Data\\JAVA\\code1\\javaweb-02-sevlet\\response\\src\\main\\resources\\2.jpg");
        System.out.println("文件的下载路径"+realPath);
        //2. 设置下载文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
        //3.设置让浏览器下载支持我们的东西
        resp.setHeader("Content-Disposition", "attachment;filename="+fileName);
        //4.获取文件下载的输入流
        FileInputStream fileInputStream = new FileInputStream(realPath);
        //5.创建缓冲区
        byte[] buffer = new byte[1024];
        int len = 0;
       // 6.获取文件输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        //7.将文件FileInputStream写入到buffer缓冲区
        while((len = fileInputStream.read(buffer))>0){
            outputStream.write(buffer,0,len);
        }
        fileInputStream.close();
        outputStream.close();

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
